package com.cherish.config.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cherish.config.jwt.JwtUtils;
import com.cherish.redis.RedisService;
import com.cherish.web.user.entity.User;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Author:MQ
 * Date:2023/12/2322:29
 * 登录认证成功处理器
 * 主要作用就是返回Json格式的数据
 */
@Component("loginSuccessHandler")
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private RedisService redisService;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 1.拿到用户信息，生成token
        User user = (User)authentication.getPrincipal();
        String token = jwtUtils.generateToken(user);
        // 2. 该token过期的时间，返回给前端
        long expireTime = Jwts.parser() // 得到DefaultJwtParser
                .setSigningKey(jwtUtils.getSecret())  //设置签名的秘钥
                .parseClaimsJws(token.replace("jwt_", ""))
                .getBody().getExpiration().getTime();
        // 3. 组装返回的数据
        LoginResult vo = new LoginResult();
        vo.setId(user.getFId() + "");
        vo.setCode(200);
        vo.setToken(token);
        vo.setExpireTime(expireTime);

        // 4. 返回json
        // SerializerFeature.DisableCircularReferenceDetect 消除循环引用
        // String res = JSONObject.toJSONString(user,SerializerFeature.DisableCircularReferenceDetect);
        String res = JSONObject.toJSONString(vo,SerializerFeature.DisableCircularReferenceDetect);
        // 设置返回格式
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream out = response.getOutputStream();
        out.write(res.getBytes("UTF-8"));
        out.flush();
        out.close();
        // 5. 把生成的token存到redis
        String tokenKey = "token_"+token;
        redisService.set(tokenKey,token,jwtUtils.getExpiration() / 1000);
        // 6. 清除验证码
        // 6.1 获取验证码
        String code = request.getParameter("code");
        // 7. 获取请求ip,删除
        String address = request.getRemoteAddr();
        String key = address + code;
        redisService.del(key);
    }
}
